package com.example.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.example.json.JSON.JSONObject;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;

@SuppressWarnings("serial")
public class JsonParsingServlet extends BaseServlet 
{
	int id = 0;
	String stock = "null";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException 
	{
		super.doGet(req, resp);
		
	    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    Key stockbookKey = KeyFactory.createKey("StockBook", "default");

	    Query query = new Query("StockEntity", stockbookKey).addSort("date", Query.SortDirection.DESCENDING);
	    List<Entity> stocks = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
	    
	    JSONObject json = new JSONObject();
	    
	    if (stocks.isEmpty() == false) 
	    {
	    	for (Entity stock : stocks) 
	        {
	            json.append("Stock", stock.getProperty("stock"));
	            json.append("Date", stock.getProperty("date"));
	            json.append("Quantity", stock.getProperty("quantity"));
	        }
	    }
		
		resp.getWriter().println(json.toString());
	}	

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
	{
		BufferedReader buff = req.getReader();
		char[] buf = new char[4 * 1024]; // 4 KB char buffer
		int len;
		
		BufferedReader reader = buff;
		
		while ((len = reader.read(buf, 0, buf.length)) != -1) 
		{
		}
		
		String json = new String(buf);
				
		JSONObject decoder = new JSONObject(new String(json));
		id = (int)decoder.getInt("quantity");
		stock = (String)decoder.getString("stock");
		
        Key stockbookKey = KeyFactory.createKey("StockBook", "default");
        
        Date date = new Date();
        Entity stockEntity = new Entity("StockEntity", stockbookKey);
        stockEntity.setProperty("stock", stock);
        stockEntity.setProperty("date", date);
        stockEntity.setProperty("quantity", id);

        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        datastore.put(stockEntity);
		
		resp.getWriter().println("OK");
	}
}
